﻿using System.Collections.Generic;
using Didaku.QEngine.Common.Entities;
using Didaku.QEngine.Common.Interfaces.Engine;
using Didaku.QEngine.Common.Wrapper.Engine;

namespace Didaku.QEngine.Methods.Adjust
{
    /// <summary>转移指定交易(Left)转移到目标队列中去(Right)
    /// </summary>
    internal class MoveToQueue : IAdjustFunc<Pair<Transaction, string>>
    {
        #region Implementation of IAdjustFunc<Pair<Transaction,string>>

        /// <summary>为调整交易与队列的动作准备的条件
        /// </summary>
        /// <value>The params.</value>
        /// <remarks></remarks>
        public Pair<Transaction, string> Condition { get; set; }

        /// <summary>执行调整交易与队列的动作
        /// </summary>
        /// <returns></returns>
        public bool Execute(IDictionary<string, ServiceLogic> logicMap)
        {
            ServiceQueue queue = FindQueue(logicMap, Condition.Second);
            Transaction transaction = Condition.First;

            if (queue != null && transaction != null)
            {
                queue.Add(transaction, false);
                return true;
            }
            return false;
        }

        private static ServiceQueue FindQueue(IDictionary<string, ServiceLogic> logicMap, string queueNumber)
        {
            ServiceQueue queue = null;
            foreach (ServiceLogic logic in logicMap.Values)
            {
                foreach (ServiceQueueGroup group in logic)
                {
                    foreach (ServiceQueue q in @group)
                    {
                        if (q.Number.Equals(queueNumber))
                            queue = q;
                    }
                }
            }
            return queue;
        }

        #endregion
    }
}